package com.digitalhuman.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;

import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class OpenAIService {
    
    private static final Logger logger = LoggerFactory.getLogger(OpenAIService.class);
    
    @Value("${openai.api.key}")
    private String apiKey;
    
    @Value("${openai.model}")
    private String model;
    
    private static final String OPENAI_API_URL = "https://api.openai.com/v1/chat/completions";
    
    private final RestTemplate restTemplate;
    
    public OpenAIService() {
        // 创建代理
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        
        // 设置超时
        factory.setConnectTimeout(10000);  // 10秒连接超时
        factory.setReadTimeout(30000);     // 30秒读取超时
        
        // 设置代理
        try {
            InetSocketAddress address = new InetSocketAddress("127.0.0.1", 7890);
            Proxy proxy = new Proxy(Proxy.Type.HTTP, address);
            factory.setProxy(proxy);
            logger.info("Proxy configured successfully");
        } catch (Exception e) {
            logger.error("Failed to configure proxy", e);
        }
        
        this.restTemplate = new RestTemplate(factory);
    }
    
    public String generateResponse(String message) {
        try {
            logger.info("Sending request to OpenAI API with message: {}", message);
            
            // 检查 API key
            if (apiKey == null || apiKey.trim().isEmpty() || apiKey.equals("your-api-key-here")) {
                logger.error("API key not configured");
                return "Error: OpenAI API key not configured. Please set your API key in application.properties";
            }

            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.setBearerAuth(apiKey);
            
            // 构建请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("model", model);
            requestBody.put("messages", List.of(
                Map.of("role", "user", "content", message)
            ));
            requestBody.put("temperature", 0.7);
            requestBody.put("max_tokens", 150);
            
            logger.debug("Request body: {}", requestBody);
            
            // 发送请求
            HttpEntity<Map<String, Object>> request = new HttpEntity<>(requestBody, headers);
            
            try {
                ResponseEntity<Map> response = restTemplate.exchange(
                    OPENAI_API_URL,
                    HttpMethod.POST,
                    request,
                    Map.class
                );
                
                logger.debug("Response status: {}", response.getStatusCode());
                logger.debug("Response body: {}", response.getBody());
                
                // 解析响应
                if (response.getBody() != null && response.getBody().containsKey("choices")) {
                    List<Map<String, Object>> choices = (List<Map<String, Object>>) response.getBody().get("choices");
                    if (!choices.isEmpty()) {
                        Map<String, Object> choice = choices.get(0);
                        Map<String, String> messageResponse = (Map<String, String>) choice.get("message");
                        return messageResponse.get("content");
                    }
                }
                
                return "Sorry, I couldn't generate a response.";
                
            } catch (HttpClientErrorException e) {
                logger.error("HTTP Client Error: {} - {}", e.getStatusCode(), e.getResponseBodyAsString(), e);
                return String.format("Error: %s - %s", e.getStatusCode(), e.getResponseBodyAsString());
            } catch (HttpServerErrorException e) {
                logger.error("HTTP Server Error: {} - {}", e.getStatusCode(), e.getResponseBodyAsString(), e);
                return "Error: OpenAI service is currently unavailable. Please try again later.";
            } catch (Exception e) {
                logger.error("Request error", e);
                return "Error: Failed to communicate with OpenAI service. " + e.getMessage();
            }
            
        } catch (Exception e) {
            logger.error("Error generating response", e);
            return "Error: " + e.getMessage() + ". Please check your network connection and proxy settings.";
        }
    }
} 